<?php
namespace App\Admin\Controllers\Shipping;

use App\Models\Basics\SysIArea;
use App\Models\Product\ProductClassify;
use App\Models\Shipping\SSkuReport;
use App\Models\Shipping\SSkuApply;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ReportController extends AdminController{

    protected $title = '提货报表';

    protected $keys = [
        'start_date' => null,
        'area_id' => null,
        'sku' => null,
        'classify_id' => null,
        'season' => null,
    ];

    protected function grid()
    {
        $startDate = request('start_date',date('Y-m-d'));
        $this->keys['start_date'] = $startDate;
        $areaId = request('area_id');
        $this->keys['area_id'] = $areaId;
        $sku = request('sku');
        $this->keys['sku'] = $sku;
        $classifyId = request('classify_id');
        $this->keys['classify_id'] = $classifyId;
        $season = request('season');
        $this->keys['season'] = $season;
        $query = $this->_initQuery($areaId,$sku,$classifyId,$season);
        $paginator = $query->paginate((int) (request("per_page",10)))->appends(Request::input());
        $shippingDate = SSkuReport::getDateRange($startDate);
        $shippingDateFirst = Arr::first($shippingDate);
        $shippingDateLast = Arr::last($shippingDate);
        $action = getAction(array_keys($this->keys));
        $options = [];
        $options['area_id'] = getOptions(SysIArea::options(),$this->keys['area_id']);
        $options['classify_id'] = getOptions(ProductClassify::options(),$this->keys['classify_id']);
        $options['season'] = getOptions(ProductClassify::$_season,$this->keys['season']);
        $downloadUrl = '/xqc/shipping/report-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('shipping.report.index', compact('paginator','options','action','startDate','sku','shippingDate','shippingDateFirst','shippingDateLast','downloadUrl'));
    }

    private function _initQuery($areaId,$sku,$classifyId,$season){
        $query = SSkuReport::query()->orderBy('id','DESC');
        if($areaId){
            $query->where('area_id',$areaId);
        }
        if($sku){
            $query->whereHas('sku',function ($query) use ($sku){
                $query->where(function ($query) use ($sku){
                    $query->where('psku_code', 'like', "%{$sku}%")
                        ->orWhere('psku_cn', 'like', "%{$sku}%");
                });
            });
        }
        if($classifyId){
            $query->whereHas('sku',function ($query) use ($classifyId){
                if($classifyId){
                    $query->where('classify_id', $classifyId);
                }
            });
        }
        if($season){
            $query->whereHas('skuClassify',function ($query) use ($season){
                $query->where('season', $season);
            });
        }
        return $query;
    }

    public function download(){
        $startDate = request('start_date',date('Y-m-d'));
        $areaId = request('area_id');
        $sku = request('sku');
        $classifyId = request('classify_id');
        $season = request('season');
        $query = $this->_initQuery($areaId,$sku,$classifyId,$season);
        $shippingDate = SSkuReport::getDateRange($startDate);
        $shippingDateFirst = Arr::first($shippingDate);
        $shippingDateLast = Arr::last($shippingDate);
        $this->_exeDownload($query, $shippingDate,$shippingDateFirst,$shippingDateLast);
    }

    private function _exeDownload($query, $shippingDate,$shippingDateFirst,$shippingDateLast){
        $title1 = ['站点','SKU','产品名称','季节性','品类'];
        $title2 = [];
        foreach($shippingDate as $label){
            $title2[] = $label.'需求';
        }
        $head = array_merge($title1,$title2);
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="提货报表.csv"',
        ]);
        $response->setCallback(function () use ($head, $query, $shippingDate,$shippingDateFirst,$shippingDateLast) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(500, function ($re) use ($fp,$shippingDate,$shippingDateFirst,$shippingDateLast){
                $data = $this->__getData($re, $shippingDate,$shippingDateFirst,$shippingDateLast);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

    private function __getData($re,$shippingDate,$sDate,$eDate)
    {
        foreach ($re as $row){
            $temp = [];
            $temp['area'] = $row->area->area ?? '';
            $temp['psku_code'] = $row->sku->psku_code ?? '';
            $temp['psku_cn'] = $row->sku->psku_cn ?? '';
            $temp['season'] = ProductClassify::$_season[$row->skuClassify->season ?? 3];
            $temp['title'] = $row->skuClassify->title ?? '';
            $applyNum = SSkuApply::getApplyNum($row->area_id,$row->psku_id,$sDate,$eDate);
            foreach($shippingDate as $i => $date){
                $temp['apply_num'.$i] = array_key_exists($date,$applyNum) ? $applyNum[$date] : 0;
            }
            yield $temp;
        }
    }
}
